#!/bin/bash

download_hosts_path=~/hosts   # hosts 下载路径
hosts_path=/etc/hosts         # 系统 hosts 保存路径
hosts_path_bak=/etc/hosts.bak # 系统 hosts 备份路径

# 下载 hosts
echo "########## downloading hosts about github to $download_hosts_path ##########"
wget -O $download_hosts_path https://gitee.com/ineo6/hosts/raw/master/hosts

# 备份 hosts
echo "########## copying $hosts_path to $hosts_path_bak ##########"
sudo cp $hosts_path $hosts_path_bak

# 删除 hosts 中原有 github 相关配置
echo "########## removing hosts about github in $hosts_path ##########"
sudo sed -i ":begin; /# GitHub Host Start/,/# GitHub Host End/ { /# GitHub Host End/! { $! { N; b begin }; }; s/# GitHub Host Start.*# GitHub Host End//; };" $hosts_path
sudo sh -c "sed -i '/^$/d' $hosts_path" # 删除系统 hosts 文件中的空行

# 更新 hosts
echo "########## updating hosts about github in $hosts_path ##########"
sudo sh -c "sed -i '/^\\s*#.*$/d' $download_hosts_path" # 删除下载 hosts 文件中的注释
sudo sh -c "sed -i '/^$/d' $download_hosts_path" # 删除下载 hosts 文件中的空行
host_value=`cat $download_hosts_path` # 读取下载 hosts 文件内容
host_value=`echo -e "\n# GitHub Host Start\n${host_value}\n# GitHub Host End"`
sudo sh -c "echo \"$host_value\" >> $hosts_path" # 将新的 hosts 内容追加到系统 hosts 文件中